package com.haoqizhe.kernel.security.config;

import cn.hutool.json.JSONUtil;
import com.haoqizhe.kernel.commons.enums.ResultCode;
import com.haoqizhe.kernel.web.result.DefaultErrorResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * security 异常处理
 * @author haoqizhe.li
 * @date 2018/10/16
 **/
@Slf4j
public class JwtAuthenticationEntryPoint implements AuthenticationEntryPoint {
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException e) throws IOException, ServletException {

        log.error(e.getMessage(),e);

        ResultCode code = ResultCode.PERMISSION_NO_ACCESS;
        HttpStatus status = HttpStatus.UNAUTHORIZED;
        if(e instanceof InsufficientAuthenticationException){
            code = ResultCode.PERMISSION_ERROR;
        }

        response.setContentType(MediaType.APPLICATION_JSON_VALUE);
        response.getWriter().write(JSONUtil.toJsonPrettyStr(DefaultErrorResult.failure(code,e, status)));
    }
}
